import ast

import jwt
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views import View
from app.url import *
from app.models import *


# 获取红娘数据接口
class MatchmakerView(View):
    def get(self, request):
        # 获取分页参数
        page = request.GET.get('page', 1)
        # 获取每页数据量
        page_size = request.GET.get('pageSize', 5)
        # 获取所有红娘数据并返回
        info = Matchmaker.objects.all()
        paginator = Paginator(info, page_size)
        # 获取当前页的数据
        page_data = paginator.page(page)
        # 组装数据并返回
        data = []
        for i in page_data:
            data.append({
                'id': i.id,
                'nickname': i.nickname,
                'url': get_server_url(request) + i.url,
                'position': i.position
            })
        return JsonResponse({
            'code': 200,
            'data': {
                'result': data
            },
            'msg': '请求成功'
        })


# 获取私人红娘信息
class PrivateMatchmakerView(View):

    def get(self, request):
        try:
            # 获取请求头中token
            userid = request.GET.get('u_id')
            # 获取私人红娘数据
            private_info = User.objects.select_related('matchmaker').get(id=userid)
            # 组装数据并返回
            data = {
                'id': private_info.matchmaker.id,  # 红娘ID
                'nickname': private_info.matchmaker.nickname,  # 红娘昵称
                'position': private_info.matchmaker.position,  # 红娘职位
                'phone': private_info.matchmaker.phone,  # 红娘电话
                'come_from': private_info.matchmaker.come_from,  # 红娘属店
                'wxUrl': get_server_url(request) + private_info.matchmaker.wxUrl,  # 微信二维码地址
                'job_number': private_info.matchmaker.job_number,  # 工号
                'avatar': get_server_url(request) + private_info.matchmaker.url  # 头像
            }
            return JsonResponse({
                'code': 200,
                'msg': 'Success',
                'data': {
                    'result': data
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'token无效 err${e}'
            })

    # 添加为我的红娘
    def post(self, request):
        try:
            requests = ast.literal_eval(request.body.decode('utf-8'))
            # 获取红娘id
            m_id = requests.get("m_id")
            # 获取用户id
            u_id = requests.get("u_id")
            User.objects.filter(id=u_id).update(matchmaker_id=m_id)
            return JsonResponse({
                'code': 200,
                'msg': '添加成功'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'添加失败：{str(e)}'
            })
